package com.sly.fuxi.demo.web;

import com.sly.fuxi.demo.service.DemoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author SLY
 * @date 2025/2/6
 */
@Slf4j
@RestController
@RequestMapping("/demo")
public class DemoController {

    @Resource
    private Executor taskWaitingExecutor;

    @Resource
    private DemoService demoService;

    @RequestMapping("demo01")
    public Object demo01() {
        return "demo01";
    }

    @RequestMapping("demo02")
    public Object demo02() throws InterruptedException {
        Object[] arr = {};
        HashMap<String, Object> map = new HashMap<>(16);
        map.put("1", "一");

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 8, 10,
                TimeUnit.SECONDS, new ArrayBlockingQueue<>(100));
        threadPoolExecutor.allowCoreThreadTimeOut(true);

        Thread.sleep(1000);
        return "demo01";
    }

    @RequestMapping("/demo03")
    public Object demo03() throws InterruptedException {
        long start = System.currentTimeMillis();
        for (int i = 0; i < 50; i++) {
            int finalI = i;
            log.info("放入线程池:{}", finalI);
            taskWaitingExecutor.execute(() -> {
                demoService.demo03(finalI);
            });
        }
        log.info("执行时间:{}", (System.currentTimeMillis() - start) / 1000);
        return "success";
    }
}
